from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import  By
import time

'''
# 切到iframe内层，再切出
wd.switch_to.frame('innerFrame') #id or name
wd.switch_to.frame(wd.find_element(By.TAG_NAME, "iframe")) # selenium元素
wd.switch_to.default_content()
# 切到链接打开的新窗口,如下：  

'''


def switch_to_widow_by_tile(wd, title:str):
    for handle in wd.window_handles:
        # 先切换到该窗口
        wd.switch_to.window(handle)
        # 得到该窗口的标题栏字符串，判断是不是我们要操作的那个窗口
        if title in wd.title:
            # 如果是，那么这时候WebDriver对象就是对应的该该窗口，正好，跳出循环，
            break


def switch_to_lastest_widow(wd):
    windows = wd.window_handles
    wd.switch_to.window(windows[-1])


wd = webdriver.Chrome(service=Service(r'/Users/tonywu/downloads/Mess/chromedriver/chromedriver'))
wd.implicitly_wait(10)

wd.get('https://www.byhy.net/cdn2/files/selenium/sample3.html')

# 点击打开新窗口的链接
link = wd.find_element(By.TAG_NAME, "a")
link.click()

# wd.title属性是当前窗口的标题栏 文本
print(wd.title)

# mainWindow变量保存当前窗口的句柄
mainWindow = wd.current_window_handle
switch_to_lastest_widow(wd)
wd.find_element(By.ID, 'sb_form_q').send_keys('翁帆\n')
time.sleep(2)
# 关闭当前窗口，切换回之前的窗口
# wd.close()
wd.switch_to.window(wd.window_handles[0]) # 第一个窗口是原始窗口
time.sleep(2)
wd.find_element(By.ID, 'outerbutton').click()

switch_to_widow_by_tile(wd, "必应")
search=wd.find_element(By.ID, 'sb_form_q')
search.clear()
search.send_keys('杨振宁\n')
time.sleep(2)
wd.switch_to.window(mainWindow)
input()
